import { HomeOutlined } from "@ant-design/icons";
import { history, useSelectedRoutes } from "@umijs/max";
import { useTextColor } from "./useTextColor";

interface iBread {
  index: number;
  path: string;
  breadcrumbName: string;
}

export const useDreadcrumb = (): any => {
  const [textColor] = useTextColor(0.8);
  const currentRoutes = useSelectedRoutes();

  const routes =
    currentRoutes?.reduce((sum: iBread[], route: any, index) => {
      const isNew = route?.params?.id === "new";
      let curBread = [
        {
          index,
          path: route?.route?.path || "",
          // 如果是新增，面包屑的名称要用新增名
          breadcrumbName:
            isNew && route?.route?.newBreadName ? route?.route?.newBreadName : route?.route?.name
        }
      ];
      let [basePath, params] = route?.route?.path?.split(":");
      if (params && currentRoutes[index - 1]) {
        basePath = basePath?.substr(0, basePath?.length - 1);
        const prevRoute: any = currentRoutes[index - 1]?.route?.children?.find(
          (child: any) => child?.path === basePath
        );

        if (prevRoute) {
          curBread = [
            {
              index,
              path: prevRoute?.path || "",
              breadcrumbName: prevRoute?.name || ""
            },
            {
              ...curBread[0],
              index: index + 1
            }
          ];
        }
      }
      return [...sum, ...curBread];
    }, []) || [];

  return {
    routes,
    itemRender: (route: iBread) => {
      switch (route?.index) {
        case 0:
          return <HomeOutlined />;
        case 1:
          return <>{route.breadcrumbName}</>;
        case 2:
          return (
            <a
              style={{ color: textColor }}
              onClick={() => {
                history.push(route?.path);
              }}
            >
              {route.breadcrumbName}
            </a>
          );
        case 3:
          return <span style={{ color: textColor }}>{route.breadcrumbName}</span>;
        default:
          return <></>;
      }
    }
  };
};
